package com.yutou.droid.UselessCode;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import com.alibaba.fastjson.JSON;

import java.lang.reflect.Field;

/**
 * Handler处理类
 */
public class MyHandlerCallback implements Handler.Callback {
    private Handler mHandler;

    public MyHandlerCallback(Handler mHandler) {
        this.mHandler = mHandler;
    }

    @Override
    public boolean handleMessage(Message msg) {
        System.out.println("接收到msg："+msg.what);
        Message message=msg;
        switch (msg.what) {
            case 100: //100为startActivity
                handleStartActivity(msg);
                break;

        }
        try {
            mHandler.handleMessage(msg);
        }catch (Exception e){
            e.printStackTrace();
            mHandler.handleMessage(message);
        }
        return true;
    }

    /**
     * 将未注册Activity的Handler替换掉已注册Activity的Handler
     * 如果不进行替换就只是单纯的劫持Activity到代理Activity了
     * @param msg
     */
    private void handleStartActivity(Message msg) {
        System.out.println("===============开始处理startActivity============");
        Object object = msg.obj;
        System.out.println("obj:"+JSON.toJSONString(object));
        try {
            Field field = object.getClass().getDeclaredField("intent");
            if (field == null) {
                System.out.println("Intent为空");
                return;
            }
            field.setAccessible(true);
            Intent intent = (Intent) field.get(object); //代理的Intent
            Intent intent_2 = intent.getParcelableExtra("oldIntent"); //被代理的Intent，即真正要展示的
            if (intent_2 == null) {
                System.out.println("intent_2为空");
                return;
            }
            System.out.println("代理的Component:"+JSON.toJSONString(intent.getComponent()));
            System.out.println("被代理的Component:"+JSON.toJSONString(intent_2.getComponent()));

            intent.setComponent(intent_2.getComponent());
            System.out.println("===============startActivity处理完毕============");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
